package utils

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"strings"
)

// return repoName of a repoUrl
// https://gitee.com/zengyif/xxxname.git => xxxname
// https://gitee.com/zengyif/xxxname     => xxxname
func RepoName(fullUrl string) string {
	parts := strings.Split(strings.TrimSuffix(fullUrl, ".git"), "/")
	return parts[len(parts)-1]
}

func GetModuleName(codePath string) (string, error) {

	goModPath := filepath.Join(codePath, "go.mod")
	data, err := ioutil.ReadFile(goModPath)
	if err != nil {
		return "", fmt.Errorf("go.mod not found: %v", err)
	}

	scanner := bufio.NewScanner(strings.NewReader(string(data)))
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if strings.HasPrefix(line, "module ") {
			parts := strings.Fields(line)
			if len(parts) < 2 {
				return "", fmt.Errorf("invalid module declaration in go.mod")
			}
			return parts[1], nil
		}
	}
	return "", fmt.Errorf("module declaration not found in go.mod")

}
